package com.easy.project.base.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mybatis-plus 自动填充字段handler
 */
@Slf4j
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "deleted", Long.class, 0L);
        String loginId = getLoginId();
        this.strictInsertFill(metaObject, "creator", String.class, loginId);
        this.strictInsertFill(metaObject, "updater", String.class, loginId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updater", String.class, getLoginId());
    }

    /**
     * 获取当前登录用户的id 没有登录默认为0
     * @return
     */
    private String getLoginId(){
        String loginId = null;
        try {
            loginId = StpUtil.getLoginIdAsString();
        }catch (NotLoginException exception){
            log.info("未登录");
        }
        if (Objects.isNull(loginId)){
            loginId = "0";
        }
        return loginId;
    }
}
